# coding=utf-8
from flask import Blueprint,request,current_app,jsonify
from db.db_utils import MySQL
from models.ydAIModel import aiModel
from datetime import datetime
import time
import configparser
import sys

ydaicontroller = Blueprint('yd_ai_controller',__name__)

"""
读取配置文件
"""
try:
    cf = configparser.ConfigParser()
    # cf.optionsxform = str  # 若出现不分大小写字符的情况 用这个
    cf.read('./conf/config.ini')
    domain = cf.get('web','domain')
except Exception as e:
    current_app.logger.debug('请确保config.ini是否存在,或配置不正确！')
    current_app.logger.debug(e)
    sys.exit(0)

@ydaicontroller.route('/api/callback', methods=['GET'])
def callback():
    with MySQL() as db:
        aimodel = aiModel()
        sql = "select tj.id,tj.user_id,tj.num,tj.type, \
                tjp.id as p_id,tjp.submit_id,tjp.task_jai_id,tjp.ai,tjp.ai_report,tjp.content,tjp.ai_para,tjp.para_str,tjp.filepath,tjp.filename from fa_task_jai tj \
                left join fa_task_jai_process tjp \
                on tjp.id = (SELECT id FROM fa_task_jai_process WHERE jai_id = tj.id and status = 0 ORDER BY createtime DESC LIMIT 1) \
                where tj.del_flag = 0 and tj.status = 0"
        # 查询出所有可执行的任务
        res = db.query_all(sql)
        if not res:
            current_app.logger.debug("暂无任务")
            return jsonify({
                "status": "completed",
                "msg": "No tasks"
            })
        start_time = datetime.now()
        current_app.logger.info(f"Starting to process")
        for process in res:
            try:
                pid = process['p_id']
                if not process['task_jai_id']:
                    current_app.logger.debug("查重未完成，跳过")
                    continue
                # 查询降AI接口返回
                outputTextRes = aimodel.outputText(process['task_jai_id'])
                # 接口错误或文件有问题，跳过
                if 'data' not in outputTextRes:
                    current_app.logger.debug("获取降AI接口异常，跳过")
                    continue
                # 降AI未完成，跳过
                if not outputTextRes['data']['status']:
                    current_app.logger.debug("AI还未生成")
                    continue
                output = outputTextRes['data']['output']
                # 根据降AI段落重组文章
                ai_para = process['para_str']
                ai_para = tuple(map(int, ai_para.split(',')))
                # 原文
                paragraphsList = aimodel.split_paragraphs(process['content'])
                # 新段落
                outputList = aimodel.split_paragraphs(output)
                # 替换指定段落
                for i, replace_idx in enumerate(ai_para):
                    paragraphsList[replace_idx - 1] = outputList[i]
                content = '\n\n\n\n'.join(item for item in paragraphsList)
                # 重组文章生成docx
                wordRes = aimodel.create_word_document(content)
                current_app.logger.debug("生成docx返回:")
                current_app.logger.debug(wordRes)
                if not wordRes:
                    current_app.logger.debug("docx文件生成异常")
                    continue
                filepath = wordRes['filepath']
                filename = wordRes['filename']
                uploadRes = aimodel.uploadApi(filepath)
                if 'error' in uploadRes:
                    current_app.logger.debug("上传查重API异常")
                    continue
                dataid = uploadRes['data']['data_id']
                taskid = uploadRes['data']['uid']
                file_url = domain + '/' + filepath.replace("\\","/")
                db.execute_many_sqls([
                    ("UPDATE fa_task_jai_process SET status = 1,updatetime = %s WHERE id = %s", 
                    (time.time(), pid)),
                    ("INSERT INTO fa_task_jai_process(jai_id, submit_id,task_id, filename, filepath,file_url,content,ai_para,last_id,createtime) VALUES (%s, %s, %s, %s, %s,%s,%s, %s, %s, %s)",
                    (process['id'], dataid,taskid, filename, filepath,file_url,content,','.join(map(str,ai_para)),pid,time.time())),
                    ("UPDATE fa_task_jai SET num = num + 1,updatetime = %s WHERE id = %s", 
                    (time.time(), process['id'])),
                ])
            except Exception as e:
                    current_app.logger.error(f"Error in processing: {str(e)}")
                    continue
        # 计算处理时间
        processing_time = (datetime.now() - start_time).total_seconds()
        current_app.logger.info(f"Completed processing in {processing_time:.2f} seconds")
        # 返回处理结果
        return jsonify({
            "status": "completed",
            "processing_time_seconds": processing_time,
        })

@ydaicontroller.route('/api/jaiydtask', methods=['GET'])
def process_items():
    with MySQL() as db:
        aimodel = aiModel()
        sql = "select tj.id,tj.user_id,tj.num,tj.type, \
                tjp.id as p_id,tjp.submit_id,tjp.task_jai_id,tjp.ai,tjp.ai_report,tjp.content,tjp.ai_para,tjp.filepath,tjp.filename from fa_task_jai tj \
                left join fa_task_jai_process tjp \
                on tjp.id = (SELECT id FROM fa_task_jai_process WHERE jai_id = tj.id and status = 0 ORDER BY createtime DESC LIMIT 1) \
                where tj.del_flag = 0 and tj.status = 0"
        # 查询出所有可执行的任务
        res = db.query_all(sql)
        if not res:
            current_app.logger.debug("暂无任务")
            return jsonify({
                "status": "completed",
                "msg": "No tasks"
            })
        try:
            # 开始流程
            current_app.logger.info(f"Starting to process")
            start_time = datetime.now()
            # 处理文章,查AI并且寻找降AI段落
            aimodel.handle_text(res,db)
            # 计算处理时间
            processing_time = (datetime.now() - start_time).total_seconds()
            current_app.logger.info(f"Completed processing in {processing_time:.2f} seconds")
            # 返回处理结果
            return jsonify({
                "status": "completed",
                "processing_time_seconds": processing_time,
            })
        except Exception as e:
            current_app.logger.error(f"Error in processing: {str(e)}")
            return jsonify({"error": str(e)}), 500

